import 'dart:convert';

import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

class MQTTService {
  final String host = '49.232.216.74';
  final int port = 1883;
  final String clientId = 'flutter_cid${DateTime.now().millisecondsSinceEpoch}';
  final String username = 'db1234';
  final String password = 'db1234'; // 填写你的密码

  late MqttServerClient client;

  Future<void> connect() async {
    client = MqttServerClient(host, clientId);
    client.port = port;
    client.keepAlivePeriod = 30;
    client.logging(on: true);
    client.useWebSocket = false; // ✅ 不使用 WebSocket
    client.secure = false; // 不使用 SSL
    client.setProtocolV311();

    client.onConnected = onConnected;
    client.onDisconnected = onDisconnected;
    client.onSubscribed = onSubscribed;

    void Function(String topic, String message)? onMessage;


    final connMess = MqttConnectMessage()
        .withClientIdentifier(clientId)
        .authenticateAs(username, password)
        .keepAliveFor(30)
        .startClean();

    client.connectionMessage = connMess;

    try {
      final connStatus = await client.connect();
      if (connStatus?.state == MqttConnectionState.connected) {
        print('✅ MQTT Connected via TCP');
      } else {
        print('❌ MQTT connection failed: ${connStatus?.returnCode}');
        disconnect();
      }
    } catch (e) {
      print('❌ MQTT TCP connect exception: $e');
      disconnect();
    }
  }

  void subscribe(String topic) {
    if (client.connectionStatus?.state == MqttConnectionState.connected) {
      client.subscribe(topic, MqttQos.atLeastOnce);
      client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> messages) {
        final recMessage = messages[0].payload as MqttPublishMessage;
        final payloadBytes = recMessage.payload.message;
        final payloadStr = utf8.decode(payloadBytes);
        print('📩 Received: $payloadStr from ${messages[0].topic}');

      });
    } else {
      print('⚠️ Cannot subscribe, not connected');
    }
  }

  void publish(String topic, String message) {
    if (client.connectionStatus?.state == MqttConnectionState.connected) {
      final builder = MqttClientPayloadBuilder();
      builder.addString(message);
      client.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!);
    } else {
      print('⚠️ Cannot publish, not connected');
    }
  }

  void disconnect() {
    print('🔌 Disconnecting...');
    client.disconnect();
  }

  void onConnected() => print('✅ Connected to MQTT broker via TCP');
  void onDisconnected() => print('⚠️ MQTT Disconnected');
  void onSubscribed(String topic) => print('📥 Subscribed to $topic');
}
